package com.huafeng.commonutil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huafeng.model.base.PageEntity;
import com.huafeng.model.base.Result;
import com.huafeng.model.enums.ResultCodeEnum;
import com.huafeng.model.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;

/**
 * @author 花风
 * @date 2023/8/16 18:29
 * @Description 校验工具类
 */
public class CheckUtils {

    private CheckUtils(){
    }

    /**
     * 检验操作是否成功
     * @param isSuccess 成功标识
     * @return 成功返回结果，失败抛出异常
     */
    public static Result check(boolean isSuccess){
        if (isSuccess){
            return Result.ok();
        }else {
            throw new BusinessException(ResultCodeEnum.SERVICE_ERROR);
        }
    }

    /**
     * 检查参数是否可以加入到条件查询对象中
     * @param queryWrapper 条件查询对象
     * @param pageEntity 分页对象
     * @param params 参数
     * @return 条件查询对象
     * @param <T> 条件查询对象的泛型
     */
    public static<T> QueryWrapper<T> checkParams(QueryWrapper<T> queryWrapper, PageEntity pageEntity, Map<String,String> params){
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (StringUtils.isNotEmpty(value) && StringUtils.isNotBlank(value)){
                if (Objects.equals(key,"createTimeBegin")){
                    queryWrapper.ge("create_time",value);
                }else if (Objects.equals(key,"createTimeEnd")){
                    queryWrapper.le("create_time",value);
                }else {
                    queryWrapper.like(key,value);
                }
            }
        }

        // 获取排序字段
        String sortField = pageEntity.getSortField();
        // 根据指定字段排序
        queryWrapper = Objects.equals(pageEntity.getSortOrder(), "desc") ? queryWrapper.orderByDesc(sortField) : queryWrapper.orderByAsc(sortField);

        return queryWrapper;
    }
}
